﻿using System;
using System.Xml.Linq;
using System.Linq;
using System.Collections.Generic;
using ClrExtensions.Net.Rest;
using MediaPortal.GUI.Library;

namespace MyNetflix2
{
    public class Episodes : Queue
    {
        private string _theTVDbKey = "";
        private User _user = null;

        /// <summary>
        /// Episodes
        /// </summary>
        /// <param name="user"></param>
        public Episodes(User user)
            : base(user)
        { _user = user; }

        /// <summary>
        /// Refresh the Recommendations Queue
        /// </summary>
        /// <param name="resource"></param>
        /// <param name="accessToken"></param>
        /// <returns></returns>
        public override List<QueueItem> Refresh(string titleId, string theTVDbId)
        {
            //--------------------------------------------------------------------------------
            // Create the Rest call
            //--------------------------------------------------------------------------------
            RestCall request = new RestCall(RestVerb.Get, titleId + "?expand=formats");

            try
            {
                //--------------------------------------------------------------------------------
                // Get the Recommendations Queue from Netflix
                //--------------------------------------------------------------------------------
                string xml = base.NetFlixUser.NetflixConnection.RequestResource(request, base.NetFlixUser.Token);

                //--------------------------------------------------------------------------------
                // Parse to Linq
                //--------------------------------------------------------------------------------
                XElement root = XElement.Parse(xml);

                //--------------------------------------------------------------------------------
                // Get the episode information
                //--------------------------------------------------------------------------------
                string bannerImage = "";

                XDocument theTVDBCallEpisodes = XDocument.Load("http://thetvdb.com/api/" + _theTVDbKey + "/series/" + theTVDbId + "/all/");
                bannerImage = "http://thetvdb.com/banners/" + theTVDBCallEpisodes.Element("Data").Element("Series").Element("fanart").Value;

                int i = 1;
                //--------------------------------------------------------------------------------
                // Add the elements to the QueueItems class
                //--------------------------------------------------------------------------------
                foreach (XElement node in root.Elements("catalog_title"))
                {
                    XElement episodeXML = null;
                    string sSeasonNumber = node.Element("title").Attribute("regular").Value.Substring(node.Element("title").Attribute("regular").Value.IndexOf("Season") + 7, 1);
                    int outSeasonNumber;

                    if(!int.TryParse(sSeasonNumber, out outSeasonNumber)) 
                    {
                        sSeasonNumber = "1";
                    }

                    if (theTVDBCallEpisodes != null)
                    {
                        IEnumerable<XElement> address = from el in theTVDBCallEpisodes.Descendants("Episode")
                                                        where (string)el.Element("EpisodeNumber").Value == (i).ToString() && (string)el.Element("SeasonNumber").Value == sSeasonNumber
                                                        select el;
                        foreach (XElement el in address)
                            episodeXML = el;
                    }

                    QueueItems.Add(new QueueItem(node, _user, episodeXML, bannerImage));
                    i++;
                }

                return QueueItems;
            }
            catch (Exception ex)
            {
                Log.Error("My NetFlix - Recommendations:Refresh(): Error - " + ex.Message);
                return null;
            }
        }
    }
}
